//
//  TSImageReloadCollectionView.m
//  CJUIKitDemo
//
//  Created by ciyouzen on 2017/9/11.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "TSImageReloadCollectionView.h"
#import <CJCollectionViewLayout/CQCollectionViewFlowLayout.h>
#import <CQDemoKit/CQTSRipeImageCollectionViewCell.h>
#import <SDWebImage/UIImageView+WebCache.h>


@interface TSImageReloadCollectionView () <UICollectionViewDataSource> {
    
}
@property (nonatomic, assign, readonly) BOOL fixBug;    /**< 是否修复bug（默认否） */

@end


@implementation TSImageReloadCollectionView

#pragma mark - Event
/*
 *  是否要修复bug
 *
 *  @param shouldFixBug 是否要修复bug（YES:修复bug; NO:重现bug）
 */
- (void)fixBug:(BOOL)shouldFixBug {
    _fixBug = shouldFixBug;
}


/// 为宽已知的collectionView，初始化列数固定的集合视图
- (instancetype)initWithFixColumn {
    CQCollectionViewFlowLayout *layout = [[CQCollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 15;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    //以下值必须二选一设置（默认cellWidthFromFixedWidth设置后，另外一个自动失效）
    layout.cellWidthFromPerRowMaxShowCount = 4;
    //layout.cellWidthFromFixedWidth = 80;
    layout.widthHeightRatio = 1.0;
    
    
    self = [super initWithFrame:CGRectZero collectionViewLayout:layout];
    if (self) {
        [self setupConfigure];
    }
    return self;
}

- (void)setupConfigure {
    /* 设置Register的Cell或Nib */
    CQTSRipeImageCollectionViewCell *registerCell = [[CQTSRipeImageCollectionViewCell alloc] init];
    [self registerClass:[registerCell class] forCellWithReuseIdentifier:@"cell"];
    
    /* 设置DataSource */
    self.dataSource = self;
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger cellCount = self.dataModels.count;
    return cellCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CQTSNetImageDataModel *dataModel = [self.dataModels objectAtIndex:indexPath.item];
    
    CQTSRipeImageCollectionViewCell *dataCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    dataCell.backgroundColor = [UIColor greenColor];
    
    // title
    dataCell.titleNameLabel.text = dataModel.name;
    
    // image
    UIImage *placeholderImage = nil;
    NSURL *imageURL = [NSURL URLWithString:dataModel.imageUrl];
    
    if (self.fixBug) {
        [dataCell.iconImageView sd_setImageWithURL:imageURL placeholderImage:placeholderImage];
    } else {
        dataCell.iconImageView.image = placeholderImage; // 非常的细节注意：当图片是异步加载的时候，必须添加此行，否则执行reload等操作的时候，在真正的图片加载下来前会出现图片的错乱问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 模拟以测试图片异步加载
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
            dispatch_async(dispatch_get_main_queue(), ^{
                dataCell.iconImageView.image = image; // 解决办法，渠道这个图片缓存起来
            });
        });
    }
    
    
    // badge
    [dataCell setupBadgeCount:dataModel.badgeCount withMaxNumber:9];
    
    return dataCell;
}



@end
